package com.renwei.yunlong.activity.me;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.renwei.yunlong.R;
import com.renwei.yunlong.YunLongApplication;
import com.renwei.yunlong.activity.work.PhotoDisplayActivity;
import com.renwei.yunlong.adapter.ImageSmallFileAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.UpdateUserIconBean;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.utils.UploadManger;
import com.renwei.yunlong.utils.UtilList;
import com.zyf.fwms.commonlibrary.utils.FormatUtil;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import github.opensource.dialog.prompt.PromptButton;
import github.opensource.dialog.prompt.PromptButtonListener;
import github.opensource.dialog.prompt.PromptDialog;

/**
 * 意见反馈--页面
 * <p>
 * Created by Administrator on 2017/8/25.
 */

public class FeedbackActivity extends BaseActivity implements View.OnClickListener, TextWatcher, ImageSmallFileAdapter.OnItemDeleteClickListener,
        AdapterView.OnItemClickListener, InvokeListener, TakePhoto.TakeResultListener, HttpTaskListener {


    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_edit)
    TextView tvEdit;
    @Bind(R.id.iv_cont)
    ImageView ivCont;
    @Bind(R.id.iv_edit)
    ImageView ivEdit;
    @Bind(R.id.iv_contacts)
    ImageView ivContacts;
    @Bind(R.id.iv_more)
    ImageView ivMore;
    @Bind(R.id.iv_scroll)
    ImageView ivScroll;
    @Bind(R.id.top_bar)
    RelativeLayout topBar;
    @Bind(R.id.iv_image)
    ImageView ivImage;
    @Bind(R.id.et_content)
    EditText etContent;
    @Bind(R.id.tv_input_number)
    TextView tvInputNumber;
    @Bind(R.id.tv_phone)
    TextView tvPhone;
    @Bind(R.id.view)
    View view;
    @Bind(R.id.et_phone)
    EditText etPhone;
    @Bind(R.id.gridview)
    GridView gridview;
    private Uri temmImageUrl;
    private ImageSmallFileAdapter adapter;
    private PromptDialog promptDialog;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private ArrayList<TImage> list;
    private List<UpdateUserIconBean> photos = new ArrayList<>();
    private int limt;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        getTakePhoto().onCreate(savedInstanceState);
        promptDialog = new PromptDialog(this);
        adapter = new ImageSmallFileAdapter(this);
        adapter.setOnItemDeleteClickListener(this);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(this);
        initView();
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        configCompress(takePhoto);
        return takePhoto;
    }

    //配置图像压缩相关
    private void configCompress(TakePhoto takePhoto) {
        CompressConfig config;
        LubanOptions option = new LubanOptions.Builder()
                .setMaxSize(1024000)
                .create();
        config = CompressConfig.ofLuban(option);
        config.enableReserveRaw(true);
        takePhoto.onEnableCompress(config, false);
    }

    private void initView() {
        ivBack.setVisibility(View.VISIBLE);
        tvEdit.setVisibility(View.VISIBLE);
        tvTitle.setText("留言建议");
        tvEdit.setText("提交");
        ivBack.setOnClickListener(this);
        tvEdit.setOnClickListener(this);
        etContent.addTextChangedListener(this);
        etContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(200), AppHelper.emojiFilter});
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_edit://提交
                String content = etContent.getText().toString().trim();
                String phone = etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    showCenterInfoMsg("内容不能为空");
                    return;
                }
                if (!FormatUtil.isMobileNO(phone)) {
                    showCenterInfoMsg("手机号不正确");
                    return;
                }
                if (content.length() > 200) {
                    showCenterInfoMsg("内容字数超过限制");
                    return;
                }
                String companyCode = "";
                if ("1".equals(companyType)) {
                    companyCode = ownerBean.getRows().getCompany().getCompanyCode();//用户信息对象中
                } else if ("2".equals(companyType)) {
                    companyCode = serviceLoginBean.getRows().getCompany().getCompanyCode();//用户信息对象中
                }
                HashMap newmap = new HashMap();
                newmap.put("ticklIntro", content);
                newmap.put("companyCode", companyCode);
                newmap.put("userName", phone);
                if (UtilList.getCount(photos) != 0) {
                    StringBuilder filenames = new StringBuilder();
                    StringBuilder attachPath = new StringBuilder();
                    StringBuilder attachSize = new StringBuilder();
                    for (UpdateUserIconBean icon : photos) {
                        filenames.append(icon.getName()).append(",");
                        attachPath.append(icon.getPath()).append(",");
                        attachSize.append(icon.getSize()).append(",");
                    }
                    if (filenames.toString().endsWith(",")) {
                        filenames = new StringBuilder(filenames.substring(0, filenames.length() - 1));
                    }
                    if (attachPath.toString().endsWith(",")) {
                        attachPath = new StringBuilder(attachPath.substring(0, attachPath.length() - 1));
                    }
                    if (attachSize.toString().endsWith(",")) {
                        attachSize = new StringBuilder(attachSize.substring(0, attachSize.length() - 1));
                    }
                    newmap.put("filenames", filenames.toString());
                    newmap.put("attachPath", attachPath.toString());
                    newmap.put("attachSize", attachSize.toString());
                }
                newmap.put("companyType", YunLongApplication.getCompanyType());
                ServiceRequestManager.getManager().middleFeedBack(this, JsonMapUtil.mapToJson(newmap), this);
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        LogUtil.d("请求结果：" + result);
        switch (requestId) {
            case 887:
                CommonBean normalBean = new Gson().fromJson(result, CommonBean.class);
                if (normalBean.getMessage().getCode() == 200) {//成功  200
                    showCenterSuccessMsg("提交成功");
                    finish();
                }
                break;
            case 998:
                UpdateUserIconBean bean = new Gson().fromJson(result, UpdateUserIconBean.class);
                photos.add(bean);
                for (TImage image : list) {
                    String image2Name = new File(image.getCompressPath()).getName();
                    if (image2Name.equals(bean.getName())) {
                        adapter.addItem(image.getCompressPath());
                    }
                }
                break;
            case 3:
                break;
            default:

                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        LogUtil.d("请求结果：" + code);
        switch (requestId) {
            case 1:
                LogUtil.d("请求结果：" + code);
                showCenterInfoMsg("提交失败");
                break;
            case 2:
                break;
            case 3:
                break;
            default:
                break;
        }

    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String temp = s.toString();

        tvInputNumber.setText(StringUtils.value(temp.length()) + "/200");

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == (adapter.getmList() == null ? 0 : adapter.getmList().size())) { // 获取本地文件
            limt = 5 - (adapter.getCount() - 1);
            if (limt > 0) {
                PromptButton cancle = new PromptButton("取消", null);
                File file = new File(this.getApplication().getCacheDir(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                temmImageUrl = Uri.fromFile(file);
                LogUtil.e("imageUri " + temmImageUrl.toString());
                promptDialog.showAlertSheet("", true, cancle,
                        new PromptButton("打开相册", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                takePhoto.onPickMultiple(limt);
                                // showTopWrongMsg("当前还可以选择"+ limt + "张图片附件");
                            }
                        }), new PromptButton("拍照", new PromptButtonListener() {
                            @Override
                            public void onClick(PromptButton button) {
                                takePhoto.onPickFromCapture(temmImageUrl);
                            }
                        }));
            } else {
                showTopWrongMsg("最多只能选择" + 5 + "张");
            }
        } else {
            // 展示图片
            ArrayList<String> list = new ArrayList<>();
            list.addAll(adapter.getmList());
            PhotoDisplayActivity.OpenActivity(this, list, position);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onDeleteClick(int position) {
        adapter.deleteItem(position);
        photos.remove(position);
    }

    @Override
    public void takeSuccess(TResult result) {
        try {
            list = result.getImages();
            for (TImage it : list) {
                File newFile = new File(it.getCompressPath());
                if (newFile.exists()) {
                    UploadManger manger = UploadManger.getManager();
                    if ("1".equals(companyType)) {
                        manger.uploadFeedBackImage(this, newFile, this, "", StringUtils.value(ownerBean.getRows().getOwnerCode()));
                    } else if ("2".equals(companyType)) {
                        manger.uploadFeedBackImage(this, newFile, this, "", StringUtils.value(serviceLoginBean.getRows().getServiceProviderCode()));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            showCenterInfoMsg(this.getString(R.string.tip_file_is_not_exist));
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }
}
